const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.json());

let db = new sqlite3.Database('sqlite:./SQL/userlite.sqlite', (err) => {
    if (err) {
        /**console.error(err.message);**/
        console.log('ERROR CODE: 10002');
        console.log('Connect to the SQLite database failed');
    }
    console.log('Connected to the SQLite database.');
});

app.post('/api/login', (req, res) => {
    const { username, password } = req.body;
    db.get('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], (err, row) => {
        if (err) {
            res.status(500).json({ "error": err.message });
            return;
        }
        if (row) {
            res.json({ "message": "success", "username": row.username });
        } else {
            res.status(401).json({ "message": "登录失败，用户名或密码错误" });
        }
    });
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
